<?php
namespace app\common\components;

use app\common\utils\facade\AideUtil;
use think\Exception;

require_once dirname(__DIR__) . DS . 'library' . DS . 'IpLocation'. DS .'IpLocation.php';
/**
 *  IP 地理位置查询
 */
class IpLocation {

    //邮件发送限数设置
    const LIMIT_KEY = 'ip_location_limit'; //邮箱发送限数 KEY
    const LIMIT_NUM = 3; //没指定时间间隔内发送邮件次数
    const LIMIT_INTERVAL = 5*60; //5分钟内只能发送3次邮件



    protected $_location = null;

    public function __construct(string $ip, string $qqwry_filepath = null)
    {
        $this->_location = \IpLocation::getLocation($ip, $qqwry_filepath);

        //如果有错抛出异常
        if (isset($this->_location['error']))
            throw new Exception($this->_location['error']);
    }

    //ip
    public function getIp(){
        return $this->_location['ip'];
    }

    //获取国家
    public function getCountry(){
        return $this->_location['country'];
    }

    //获取省会
    public function getProvince(){
        return $this->_location['province'];
    }

    //获取城市
    public function getCity(){
        return $this->_location['city'];
    }

    //获取运营商
    public function getIsp(){
        return $this->_location['isp'];
    }


    //获取区域
    public function getArea(){
        return $this->_location['area'];
    }

    //获取json信息
    public function getJson(){
        return json_encode($this->_location, JSON_UNESCAPED_UNICODE);
    }

    //获取全部数据
    public function getInfo(){
        return $this->_location;
    }

    /**
     * 频率限制
     * @param int|null $num
     * @param int|null $interval
     * @return $this
     * @throws Exception
     */
    public function limit(int $num=null, int $interval=null){

        //邮件限速 5分钟内只能发送3条
        if( !AideUtil::setLimit(static::LIMIT_KEY, $num?:static::LIMIT_NUM, $interval?:static::LIMIT_INTERVAL) ){
            throw new Exception('操作次数太多，休息一下吧。');
        }

        return $this;
    }

}